<template>
  <DialogBox
    title="设置可见范围"
    v-model="dialogVisible"
    width="600"
    class="select-department-personnel"
  >

    <div class="warp">
      <div class="warp-tips">
        选中员工后，该智能体在员工智能体列表下可见
      </div>
      <el-row class="warp-content">
        <el-col :span="24" class="warp-content-search">
          <el-input
            placeholder="搜索员工姓名"
            class="input-with-select"
            v-model="searchForm.name"
            @input="handelSearch"
            clearable
          >
          >
            <template #prepend>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="8" class="warp-content-left">
          <el-tree
            highlight-current
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
          />
        </el-col>
        <el-col :span="16" class="warp-content-right" v-loading="pageLoading">
          <el-scrollbar>
            <PageEmpty 
              v-if="!personList.length && !loading" 
              :type="'1'" 
              size="260px"
              text1="该部门没有员工" 
              text2="  " 
            />
            <div v-else>
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
              全选
              </el-checkbox>
              <el-checkbox-group v-model="checkList" >
                <el-space direction="vertical" alignment="flex-start">
                  <el-checkbox v-for="(v) in personList" :key="v.id" :label="v.name" :value="v" />
                </el-space>
              </el-checkbox-group>
            </div>
          </el-scrollbar>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <span class="num">
          已选{{ checkList.length }}人
        </span>
        <el-button @click.prevent="dialogVisible = false" :loading="loading">
          取消
        </el-button>
        <el-button type="primary" @click="submitHandle" :loading="loading">
          保存
        </el-button>
      </span>
    </template>
  </DialogBox>
</template>
<script setup lang="ts">
import DialogBox from '@/components/dialog-box/index.vue'
import { Search } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { findOrgByTenantId } from '@/servers/base/jichu/api/zuzhi'
import { getBaseEmployeeByOrgId } from '@/servers/base/jichu/api/yuangong'
import { debounce } from 'lodash'

const treeData = ref<any>([])
const personList = ref<any>([])
const activeClick: any = ref<any>({})


const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id'
};

const props = defineProps({
  data: {
    type: Array<any>,
    default: () => []
  },
})
const emit = defineEmits(['submit'])

const checkList = ref([]);
const loading = ref(false);
const pageLoading = ref(false);
const searchForm = ref({
  orgId: '',
  name: '',
});

// 在 script setup 中添加以下代码
const checkAll = ref(false);
const isIndeterminate = ref(false);

// 处理全选逻辑
const handleCheckAllChange = (val: boolean) => {
  checkList.value = val ? personList.value.map((v: any) => ({ id: v.id, name: v.name })) : [];
  isIndeterminate.value = false;
};

// 监听 checkList 的变化
watch(checkList, (newVal) => {
  if(!newVal.length){
    checkAll.value = false;
    isIndeterminate.value = false;
  } else {
    const isAllChecked = personList.value.every((person: any) => 
      newVal.some((checked: any) => checked.id === person.id)
    );

    const isSomeChecked = personList.value.some((person: any) => 
      newVal.some((checked: any) => checked.id === person.id)
    );

    checkAll.value = isAllChecked;
    isIndeterminate.value = isSomeChecked && !isAllChecked;
  }
 
}, { deep: true });

watch(personList, (newVal) => {
  if(!newVal.length){
    checkAll.value = false;
    isIndeterminate.value = false;
  } else {
    const isAllChecked = newVal.every((person: any) => 
      checkList.value.some((checked: any) => checked.id === person.id)
    );

    const isSomeChecked = newVal.some((person: any) => 
      checkList.value.some((checked: any) => checked.id === person.id)
    );

    checkAll.value = isAllChecked;
    isIndeterminate.value = isSomeChecked && !isAllChecked;
  }
}, { deep: true });

const debouncedHandelSearch = debounce(() => {
  getPerson();
}, 300);
const handelSearch = () => {
  debouncedHandelSearch()
}
const handleNodeClick = (item: any) => {
  // 请求人员数据
  activeClick.value = item
  searchForm.value.orgId = item.id
  getPerson()
}

const getPerson = () => {
  pageLoading.value = true
  const param: any = { 
    orgId: searchForm.value.orgId, 
    name: searchForm.value.name 
  }
  if (param.orgId === 'all') delete param.orgId
  if (param.name === '') delete param.name
  // searchForm
  getBaseEmployeeByOrgId(param).then((res: any) => {
    personList.value = [...res.data.data]
  }).finally(() => {
    pageLoading.value = false
  })
}

const dialogVisible = ref(false);
const open = (activeList = []) => {
  console.log('open....', activeList);
  dialogVisible.value = true
  getTree();
  checkList.value = [...activeList]
}

const submitHandle = () => {
  dialogVisible.value = false;
  emit('submit', checkList.value);
}

const getTree = () =>{
  // @ts-ignore
  findOrgByTenantId().then((res) => {
    if (Array.isArray(res.data.data) && res.data.data.length ) {
      treeData.value = [{ id: 'all', name: "全部" }, ...res.data.data]
    }
  })
}


defineExpose({ open })
</script>

<style lang="scss" scoped>
.select-department-personnel {
  .warp {
    &-tips {
      font-weight: 400;
      font-size: 14px;
      color: #8C8C8C;
      line-height: 20px;

    }
    &-content {
      width: 100%;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #DFE0E3;
      margin-top: 8px;
      margin-bottom: 20px;
      padding: 12px;
      &-search {
        margin-top: 12px;
        margin-bottom: 11px;
      }
      &-left {
        background: #F6F6F6;
        border-radius: 4px 4px 4px 4px;
        height: 410px;
        padding: 10px;
        overflow-y: scroll;
        .el-tree {
          background: #F6F6F6;;
        }
      }
      &-right {
        height: 410px;
        overflow-y: scroll;
        padding: 10px 0px 10px 30px;
      }
    }
  }
  .dialog-footer {
    position: relative;
    .num {
      position: absolute;
      left: 30px;
      color: #8C8C8C;
      font-size: 14px;
      top: 10px;
    }
  }
}
</style>
